package com.cross.object;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cross.annotation.DataCrossField;
import com.cross.core.AbstractWriter;
import com.cross.core.Column;
import com.cross.core.Header;

public class SimpleObjectWriter<T> extends AbstractWriter {
	
	private List<T> list;
	private Class<T> clazz;
	private Field[] fields;
	private Map<Column, Field> map = new HashMap<Column, Field>();
	
	
	public SimpleObjectWriter(List<T> list, Header header, Class<T> clazz){
		this.list = list;
		this.header = header;
		this.clazz = clazz;
		fields = clazz.getDeclaredFields();
		for(Column column : header.getColumns()){
			for(Field f : fields){
				DataCrossField dataCrossField = (DataCrossField) f.getAnnotation(DataCrossField.class);
				if(dataCrossField != null){
					if(dataCrossField.title().equalsIgnoreCase(column.getTitle())){
						f.setAccessible(true);
						map.put(column, f);
					}
				}
			}
		}
	}
	
	@Override
	protected void writeRow() {
		try {
			T obj = clazz.newInstance();
			int i = 0;
			for(Column column : header.getColumns()){
				Field field = map.get(column);
				field.setAccessible(true);
				field.set(obj, currentRow.getItem(i++).get());
			}
			list.add(obj);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void close() {
		
	}

}
